<!-- 用户管理 -->
<template>
  <div class="app-container">
    <!-- 用户列表 -->
    <el-col>
      <div v-if="isShowSearchBtn" class="search-container">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="关键字" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="关键字"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>

          <el-form-item label="创建时间">
            <el-date-picker
              class="!w-[240px]"
              v-model="dateTimeRange"
              type="daterange"
              range-separator="~"
              start-placeholder="开始时间"
              end-placeholder="截止时间"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>

          <el-form-item label="状态" prop="is_hid">
            <el-select
              v-model="queryParams.is_hid"
              placeholder="全部"
              clearable
              class="!w-[100px]"
            >
              <el-option label="启用" value="0" />
              <el-option label="禁用" value="1" />
            </el-select>
          </el-form-item>

          <el-form-item label="发布状态" prop="is_push">
            <el-select
              v-model="queryParams.is_push"
              placeholder="全部"
              clearable
              class="!w-[120px]"
            >
              <el-option label="待推送" value="-1" />
              <el-option label="已推送" value="0" />
              <el-option label="发布中" value="1" />
              <el-option label="发布失败" value="2" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleQuery">
              <i-ep-search />搜索
            </el-button>
            <el-button @click="resetQuery"> <i-ep-refresh />重置 </el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-card shadow="never" class="table-container">
        <template #header>
          <div class="flex justify-between">
            <div>
              <el-button
                v-hasPerm="['wechatarticle@add']"
                type="success"
                @click="openDialog()"
              >
                <i-ep-plus />新增
              </el-button>
              <el-button
                v-hasPerm="['wechatarticle@del']"
                type="danger"
                v-if="removeIds.length > 0"
                @click="handleDelete()"
              >
                <i-ep-delete />删除
              </el-button>
            </div>
            <div>
              <span style="font-size: 14px"
                >本月已发布
                <el-tag key="已发布" type="success" effect="dark">{{
                  push_num
                }}</el-tag>
                条</span
              >
              <el-button
                class="ml-3"
                @click="handleSearchShowBtn"
                icon="Search"
                circle
              />
              <el-button
                class="ml-3"
                title="刷新"
                @click="handleQuery"
                icon="Refresh"
                circle
              />
            </div>
          </div>
        </template>

        <el-table
          v-loading="loading"
          :data="pageData"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            key="id"
            label="ID"
            align="center"
            prop="id"
            width="100"
            sortable="custom"
          />
          <el-table-column label="名称" align="center" prop="title" />
          <el-table-column label="封面图" width="180px" align="center">
            <template #default="scope">
              <el-image
                v-if="scope.row.thumb_img"
                style="width: 120px; height: 32px"
                :src="scope.row.thumb_img"
              />
            </template>
          </el-table-column>
          <el-table-column label="状态" min-width="60px" align="center">
            <template #default="scope">
              <el-tag
                v-if="scope.row.is_push === -1"
                key="待推送"
                type="info"
                effect="dark"
                >待推送</el-tag
              >
              <el-tag
                v-if="scope.row.is_push === 0"
                key="已推送"
                type="success"
                effect="dark"
                >已推送</el-tag
              >
              <el-tag
                v-if="scope.row.is_push === 1"
                key="发布中"
                type="primary"
                effect="dark"
                >发布中</el-tag
              >
              <el-tag
                v-if="scope.row.is_push > 1"
                key="发布失败"
                type="danger"
                effect="dark"
                >发布失败</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="作者" align="center" prop="author" />
          <el-table-column label="排序" align="center" prop="sort" />
          <el-table-column label="状态" align="center" prop="is_hid">
            <template #default="scope">
              <el-tag
                effect="dark"
                :type="scope.row.is_hid == 0 ? 'success' : 'danger'"
              >
                {{ scope.row.is_hid == 0 ? "启用" : "禁用" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="created_at" />
          <el-table-column label="操作" fixed="right" width="220">
            <template #default="scope">
              <el-button
                v-hasPerm="['wechatarticle@edit']"
                type="success"
                @click="openDialog(scope.row.id)"
                circle
                title="编辑"
              >
                <i-ep-edit />
              </el-button>
              <el-button
                v-hasPerm="['wechatarticle@del']"
                circle
                type="danger"
                title="删除"
                @click="handleDelete(scope.row.id)"
              >
                <i-ep-delete />
              </el-button>
              <el-button
                v-if="scope.row.is_push == 0 || scope.row.is_push > 1"
                v-hasPerm="['wechatarticle@push']"
                type="primary"
                @click="push(scope.row.id)"
                circle
                title="发布"
              >
                <i-ep-flag />
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.p"
          v-model:limit="queryParams.limit"
          @pagination="handleQuery"
        />
      </el-card>
    </el-col>
    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <!-- 新增/编辑表单 -->
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="formData.author" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="摘要" prop="digest">
          <el-input
            v-model="formData.digest"
            type="textarea"
            placeholder="请输入摘要"
          />
        </el-form-item>
        <el-form-item label="封面图" prop="thumb_img">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="headers"
          >
            <img
              v-if="formData.thumb_img"
              :src="formData.thumb_img"
              class="avatar"
              alt=""
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <editor
            v-model="formData.content"
            useType="wechat"
            style="height: calc(40vh - 100px); z-index: 999"
          />
        </el-form-item>
        <br /><br /><br /><br />
        <el-form-item label="阅读原文链接" prop="url">
          <el-input v-model="formData.url" placeholder="请输入阅读原文链接" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="formData.sort" placeholder="0" />
        </el-form-item>
      </el-form>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "MemberLabel",
  inheritAttrs: false,
});
import Editor from "@/components/WangEditor/index.vue";
import {
  getArticlePage,
  deleteArticle,
  addArticle,
  getArticleForm,
  updateArticle,
  pushArticle,
} from "@/api/wechatArticle";
import {
  ArticleQuery,
  ArticlePage,
  ArticleForm,
} from "@/api/wechatArticle/types";
import { ElLoading, UploadProps } from "element-plus";

const queryFormRef = ref(ElForm); // 查询表单
const isShowSearchBtn = ref(false);
const userFormRef = ref(ElForm); // 表单
const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除ID集合 用于批量删除
const queryParams = reactive<ArticleQuery>({
  p: 1,
  limit: 10,
});
const total = ref(0); // 数据总数
const push_num = ref(0);
const pageData = ref<ArticlePage[]>(); // 分页数据
const dateTimeRange = ref([]);

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: "55%",
  title: "",
});

// 用户表单数据
const formData = reactive<ArticleForm>({});

// 校验规则
const rules = reactive({
  title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
  content: [{ required: true, message: "内容不能为空", trigger: "blur" }],
  thumb_img: [{ required: true, message: "封面图不能为空", trigger: "blur" }],
  author: [{ required: true, message: "作者必选", trigger: "blur" }],
});

const uploadUrl = ref(
  import.meta.env.VITE_APP_API_URL + "/admin/wechatArticle/upload"
);
const headers = ref({
  Authorization: localStorage.getItem("accessToken"),
});
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  formData.thumb_img = response.data.url;
};
const imageType = ["image/jpeg", "image/png", "image/jpg"];

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (!imageType.includes(rawFile.type)) {
    ElMessage.error("图片格式不正确");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不超过 2MB!");
    return false;
  }
  return true;
};

watch(dateTimeRange, (newVal) => {
  Object.assign(queryParams, { time: newVal });
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getArticlePage(queryParams)
    .then(({ data }) => {
      pageData.value = data.items;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.p = 1;
  dateTimeRange.value = [];
  queryParams.time = undefined;
  handleQuery();
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate((valid: any) => {
    const router = useRouter();
    if (valid) {
      const ids = formData.id;
      const loading = ElLoading.service({
        lock: true,
        text: ids ? "修改提交中..." : "保存中...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      if (ids) {
        updateArticle(formData)
          .then(() => {
            loading.close();
            closeDialog();
            ElMessage.success("修改成功");
          })
          .finally(() => loading.close());
      } else {
        addArticle(formData)
          .then(() => {
            loading.close();
            closeDialog();
            ElMessage.success("新增成功");
          })
          .finally(() => loading.close());
      }
    }
  });
}, 3000);

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

function push(id?: number) {
  if (!id) {
    ElMessage.warning("请选择要推送的文章");
    return;
  }
  const loading = ElLoading.service({
    lock: true,
    text: "发布中...",
    background: "rgba(0, 0, 0, 0.7)",
  });
  ElMessageBox.confirm(
    "确认是发将文章发布至微信公众号，发布后将无法撤回?",
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(function () {
    pushArticle({ ids: id })
      .then(() => {
        loading.close();
        resetQuery();
        ElMessage.success("操作成功");
      })
      .finally(() => loading.close());
  });
}

/** 删除用户 */
function handleDelete(id?: number) {
  const ids = id || removeIds.value;
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteArticle({ ids: ids }).then(() => {
      handleQuery();
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

//收起展开搜索按钮
function handleSearchShowBtn() {
  isShowSearchBtn.value = isShowSearchBtn.value === false;
}

/**
 * 打开弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 * @param id ID
 */
async function openDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改";
    getArticleForm(id).then(({ data }) => {
      Object.assign(formData, { ...data });
    });
  } else {
    dialog.title = "新增";
  }
}

/**
 * 关闭弹窗

 */
function closeDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();

  formData.id = undefined;
  handleQuery();
}

onMounted(() => {
  handleQuery();
});
</script>

<style>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  width: 10rem;
  cursor: pointer;
  display: inline-block;
  overflow: hidden;
  text-align: center;
  height: 5rem;
  line-height: 5rem;
}
.el-upload {
  width: 100%;
  height: 100%;
}
.avatar {
  width: 100%;
  height: 5rem;
  line-height: 5rem;
  border-radius: 6px;
}
</style>
